<?php
//Redirect to another page or site
function redirectPage($url,$decode = true)
{
	if($decode)
		die('<meta http-equiv="refresh" content="0;URL='. urldecode($url) .'">');
	else
		die('<meta http-equiv="refresh" content="0;URL='.($url) .'">');
}
function redirectPageJavascript($url)
{
	echo "<script language='javascript'>javaScript:location.href = '" . urldecode($url) . "';</script>";
}
function redirectPagePHP($url)
{
	header('Location: ' . $url);
}
function redirectIframePage($url,$parent_page = false)
{
 if($parent_page == false)
  echo "<script>window.location.href = '".$url."';</script>"; 
 else
  echo "<script>window.top.location.href = '".$url."';</script>"; 
 exit();
}
function javascriptAlert($message)
{
	echo "<script language='javascript'>alert('$message');</script>";
}
function closeCurrentPageAndRefreshParentPage()
{
	echo "<script language='javascript'>JavaScript:window.opener.location.href = window.opener.location.href; window.close();</script>";
}
function selfURL($endcode = false)
{
	$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	$url = $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
	if($endcode)
		$url = urlencode($url);
	return $url;
}
function strLeft($s1, $s2) {
	return substr($s1, 0, strpos($s1, $s2));
}
function strRight($s1, $s2) {
	return substr($s1, 0, strrpos($s1, $s2));
}
function curPageName()
{
	return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
function process_url($str, $para = "lang")
{
	$result = "";
	if($str != "" && strpos($str, "?"))
	{
		$result = "";
		$str = str_replace($para, "temp", $str);
		$cmd = preg_split("/[?&]/", $str);
		$i = 0;
		foreach($cmd as $item)
		{
			if(!preg_match("/temp/", $item) || $i == 0)
			{
				if(substr($item, strpos($item,".php")) == ".php")
					$result .= $item . "?";
				else
				{
					if(substr($item, strlen($item)-1 != '?'))
						$result .= $item . "&";
					else
						$result .= $item;
				}
			}
			$i ++;
		}
		$result = trim($result, "?");
		$result = trim($result, "&");

		if(substr($result, strpos($result,".php")) == ".php")
			$result .=  "?$para=";
		else
			$result .=  "&$para=";
	}
	else
	{
		//$result = basename($_SERVER['SCRIPT_FILENAME']) . "?$para=";
		
	}
	return $result;
}
function getAllGetParams($exclude_array = '') 
{
	global $HTTP_GET_VARS;
	
	if ($exclude_array == '') $exclude_array = array();
	
	$get_url = '';
	
	reset($HTTP_GET_VARS);
	while (list($key, $value) = each($HTTP_GET_VARS)) 
	{
	  if (($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_array))) 
		$get_url .= $key . '=' . $value . '&';
	}	
	return $get_url;
}
function notNull($value) 
{
	if (is_array($value)) {
	  if (sizeof($value) > 0) {
		return true;
	  } else {
		return false;
	  }
	} else {
	  if ( (is_string($value) || is_int($value)) && ($value != '') && ($value != 'NULL') && (strlen(trim($value)) > 0)) {
		return true;
	  } else {
		return false;
	  }
	}
}
//Start db
function insert_db($tableName, $fieldsValues, $primaryColumn = "", &$primaryValue = "", $addMessage = true, $auto_set_primaryColumn = true)
{
	if($primaryColumn != "" && $primaryValue >0)
	{
		$exist_id = $GLOBALS["db_mysql"]->get_field_value("Select $primaryColumn From $tableName Where $primaryColumn = '$primaryValue'", $primaryColumn);
	}
	else
	{
		$exist_id = 0;
	}
	
	if($primaryValue != "" && $primaryValue > 0 && $exist_id > 0)
	{
		$where = $primaryColumn . " = '" . $primaryValue . "'";
		$GLOBALS["db_mysql"]->mysql_update($tableName, $fieldsValues, $where);
		$message = MESSAGE_UPDATE;
	}
	else
	{
		if(isset($fieldsValues['date_created']) == false)
			$fieldsValues['date_created'] = date('Y-m-d H:i:s');
		$GLOBALS["db_mysql"]->mysql_insert($tableName, $fieldsValues);
		$message = MESSAGE_INSERT;
		if($auto_set_primaryColumn == true)
			$primaryValue = $GLOBALS["db_mysql"]->get_mysql_insert_id();
	}
	$err = $GLOBALS["db_mysql"]->get_errors();
	if (!$GLOBALS["db_mysql"]->is_errors())
	{
		if($addMessage)
			clsErrorMessages::addMessage($message, "success");
		return true;
	}
	return false;
}
//Start db [End]
function getPermission($module_directory, $user_id = "")
{
	return array('Admin', 'F', 1);

	$user_id = is_numeric($user_id) ? $user_id : get_loginInfo($sessionName, "user_id");

	$result = array('','','');
	$permission = "N";

	$sql = "Select modules.module_name, users.user_type , module_user.permission From modules, module_user, users
			Where modules.module_id = module_user.module_id And module_user.user_id = users.user_id
			And modules.module_directory = '$module_directory' And users.user_id = '$user_id'";
	//echo $sql;
	$rows =  $GLOBALS["db_mysql"]->query($sql);
	$row = $GLOBALS["db_mysql"]->fetch_array($rows);
	if($row)
	{
		$user_type = $row['user_type'];
		if($user_type == 'Admin')
		{
			$permission = 'F';
		}
		else
		{
			$permission = $row['permission'];
		}
		if($permission == "")	$permission = 'N';
		$result = array($user_type, $permission, $user_id);
	}
	return $result;
}
function check_permission($user_type_login, $permission)
{
	if($user_type_login != 'Admin')
	{
		if($permission == 'N')
			RedirectPage('../../errors.php');
	}
}
function get_id_delete()
{
	$itemsDelete = "''";
	if(isset($_POST['hidden_selectedItems']))
	{
		$selectedItem = $_POST['hidden_selectedItems'];
		$items = explode(';', $selectedItem);
		$i = 0;
		foreach ($items as $item)
		{
			if($item != "")
			{
				$itemsDelete .= ",";
				$itemsDelete .= "'" . $item . "'";
				$i++;
			}
		}
	}
	return $itemsDelete;
}
function deleteListItems($objDelete, $addMessage = true)
{
	if(is_array($objDelete))
	{
		if(isset($_POST['hidden_submitType']) && $_POST['hidden_submitType'] == 'delete' )
		{
			if(isset($_POST['hidden_selectedItems']) && $_POST['hidden_selectedItems'] != '' )
			{
				$selectedItem = $_POST['hidden_selectedItems'];
				$items = explode(';', $selectedItem);
				$itemsDelete = "";
				$i = 0;
				foreach ($items as $item)
				{
					if($item != "")
					{
						if($i != 0)
							$itemsDelete .= ",";
						$itemsDelete .= "'" . $item . "'";
						$i++;
					}
				}
				while (list($key, $value) = each($objDelete))
				{
					$sql = "Delete From " . $key . " Where ". $value ." in(" . $itemsDelete . ")";
					$delete_result = $GLOBALS["db_mysql"]->query($sql);
					//echo "<br>" . $sql;
				}
				if($addMessage && !$GLOBALS["db_mysql"]->is_errors())
					clsErrorMessages::addMessage(MESSAGE_DELETE, "success");
			}
			else
			{
				clsErrorMessages::addMessage("Delete value is invalid.", "error");
			}
		}
	}
	else
	{
		$delete_result = $GLOBALS["db_mysql"]->query($objDelete);
		if(!$GLOBALS["db_mysql"]->is_errors())
			clsErrorMessages::addMessage(MESSAGE_DELETE, "success");
	}
}
function deleteListPreview($objDelete, $addMessage = true)
{
	if(is_array($objDelete))
	{
		if(isset($_POST['hidden_submitType']) && $_POST['hidden_submitType'] == 'delete' )
		{
			if(isset($_POST['hidden_selectedItems']) && $_POST['hidden_selectedItems'] != '' )
			{
				$selectedItem = $_POST['hidden_selectedItems'];
				$items = explode(';', $selectedItem);
				$itemsDelete = "";
				$i = 0;
				foreach ($items as $item)
				{
					if($item != "")
					{
						if($i != 0)
							$itemsDelete .= ",";
						$itemsDelete .= "'" . $item . "'";
						$i++;
					}
				}
				while (list($key, $value) = each($objDelete))
				{
					$sql = "Delete From " . $key . " Where ". $value ." in(" . $itemsDelete . ")";
					$delete_result = $GLOBALS["db_mysql"]->query($sql);
					//echo "<br>" . $sql;
					//echo "<br>" . $sql;
				}
				if($addMessage && !$GLOBALS["db_mysql"]->is_errors())
					clsErrorMessages::addMessage(MESSAGE_DELETE, "success");
			}
			else
			{
				clsErrorMessages::addMessage("Delete value is invalid.", "error");
			}
		}
	}
	else
	{
		$delete_result = $GLOBALS["db_mysql"]->query($objDelete);
		if(!$GLOBALS["db_mysql"]->is_errors())
			clsErrorMessages::addMessage(MESSAGE_DELETE, "success");
	}
}
function deleteListItemsVideoNominee($objDelete, $addMessage = true)
{
	if(is_array($objDelete))
	{
		if(isset($_POST['hidden_submitType']) && $_POST['hidden_submitType'] == 'delete' )
		{
			if(isset($_POST['hidden_selectedItems']) && $_POST['hidden_selectedItems'] != '' )
			{
				$selectedItem = $_POST['hidden_selectedItems'];
				$items = explode(';', $selectedItem);
				$itemsDelete = "";
				$i = 0;
				foreach ($items as $item)
				{
					if($item != "")
					{
						if($i != 0)
							$itemsDelete .= ",";
						$itemsDelete .= "'" . $item . "'";
						$i++;
					}
				}
				while (list($key, $value) = each($objDelete))
				{
					$sql = "Delete From " . $key . " Where ". $value ." in(" . $itemsDelete . ")";
					$delete_result = $GLOBALS["db_mysql"]->query($sql);
					//echo "<br>" . $sql;						
				}
				if($addMessage && !$GLOBALS["db_mysql"]->is_errors())
					clsErrorMessages::addMessage(MESSAGE_DELETE, "success");
			}
			else
			{
				clsErrorMessages::addMessage("Delete value is invalid.", "error");
			}
		}
	}
	else
	{
		$delete_result = $GLOBALS["db_mysql"]->query($objDelete);
		if(!$GLOBALS["db_mysql"]->is_errors())
			clsErrorMessages::addMessage(MESSAGE_DELETE, "success");
	}
}
function updateActivate()
{
	if(isset($_POST['hidden_submitType']) && $_POST['hidden_submitType'] == 'update')
	{
		$hidden_str_id = $_POST['hidden_str_id'];
		$arrID = explode(";", $hidden_str_id);
		$activate_id = ""; $deactivate_id = "";
		foreach($arrID as $user_id)
		{
			if($user_id != "")
			{
				if(isset( $_POST['activate*' . $user_id] ) == 1)
					$activate_id .= "'$user_id';";
				else
					$deactivate_id .= "'$user_id';";
			}
		}
		if($activate_id != "")
		{
			$sql = "Update users Set activate = 1 Where user_id IN (". str_replace(";", ",", trim($activate_id, ";")) .")";
			$rows = $GLOBALS["db_mysql"]->query($sql);
		}
		if($deactivate_id != "")
		{
			$sql = "Update users Set activate = 0 Where user_id IN (". str_replace(";", ",", trim($deactivate_id, ";")) .")";
			$rows = $GLOBALS["db_mysql"]->query($sql);
		}
		clsErrorMessages::addMessage(MESSAGE_UPDATE, "success");
	}
}
function format_date_db_input($str_date)
{
	return date("y-m-d", strtotime($str_date));
}
function format_date($str_date, $format = "")
{
	$format = $format == "" ? FORMAT_DATE : $format;
	$str = date($format, strtotime($str_date));
	return $str;
}
function format_date_hrs($original='', $format="%d/%m/%Y %I:%M:%S %p") 
{
	$format = ($format=='date' ? "%m-%d-%Y" : $format);
	$format = ($format=='datetime' ? "%m-%d-%Y %H:%M:%S" : $format);
	$format = ($format=='mysql-date' ? "%Y-%m-%d" : $format);
	$format = ($format=='mysql-datetime' ? "%Y-%m-%d %H:%M:%S" : $format);
	return (!empty($original) ? strftime($format, strtotime($original)) : "" );
} 
function format_date_detail($original='', $format="%d/%m/%Y, %I:%M") 
{
	$arr = array("Sun"=>"Chủ nhật", "Mon"=>"Thứ hai", "Tue"=>"Thứ ba", "Wed"=>"Thứ tư", "Thu"=>"Thứ năm", "Fri"=>"Thứ sáu", "Sat"=>"Thứ bảy");
	
	$format = ($format=='date' ? "%m-%d-%Y" : $format);
	$format = ($format=='datetime' ? "%m-%d-%Y %H:%M:%S" : $format);
	$format = ($format=='mysql-date' ? "%Y-%m-%d" : $format);
	$format = ($format=='mysql-datetime' ? "%Y-%m-%d %H:%M:%S" : $format);
	$day = date("D", strtotime($original));
	$day = $arr[$day];
	return $day . ", " .  (!empty($original) ? strftime($format, strtotime($original)) : "" ) . " GMT+7";
}
function format_dmy_To_mySqlDate($start_date)
{
	if($start_date == '')
		return $start_date;
    list($d,$m,$y) = preg_split("/[\/\.-]/",$start_date);
    
	//$m = checkMonthDay($m);
	//$d = checkMonthDay($d);
	$start_date = $y . "-" . $m . "-" . $d;
	return $start_date;
}
function checkMonthDay($d)
{
	if(strlen($d) == 1)
		return '0' . $d;
	return $d;
}
function isValidEmail($email)
{
	$email = trim($email);
	if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email))
	{
	  return true;
	}
	else
	{
	  return false;
	}
}
function get_loginInfo($sessionName, $field)
{
	$array = NULL;
	if(isset($_SESSION[$sessionName]))
		$array = $_SESSION[$sessionName];
	if($array != NULL)
	{
		for ($i = 0; $i < count($array); $i++)
		{
			$key = key($array);
			$val = $array[$key];
			if ($key == $field)
			{
				return $val;
			}
			next($array);
		}
	}
	return "";
}
function get_item_in_session_array($sessionName, $field)
{
	$array = $_SESSION[$sessionName];
	for ($i = 0; $i < count($array); $i++)
	{
		$key = key($array);
		$val = $array[$key];
		if ($key == $field)
		{
			return $val;
		}
		next($array);
	}
	return "";
}
function roundNumber($number, $precisiion = 2)
{
	$number = str_replace(",", ".", $number);
	return round($number, $precisiion);
}
function formatText($text)
{
	if (($newResult = iconv("ISO-8859-1", "UTF-8", $text)) !== FALSE)
	{
	  return $newResult;
	}
	return $text;
}
function toNumber($number)
{
	$number = str_replace(",", ".",$number);
	$number = $number > 0 ? $number : 0;
	return $number;
}
function create_dir($create_folder)
{
	if(!is_dir($create_folder))
	{
		if(!@mkdir($create_folder, 0777))
		{				
			@chmod($create_folder, 0777);
			return false;
		}
	}
	return true;
	/*		
	if($_SERVER['SERVER_NAME'] == "localhost")
	{
		if(!is_dir($create_folder))
		{
			if(!@mkdir($create_folder, 0777))
			{				
				chmod($create_folder, 0777);
				return false;
			}
		}
		return true;
	}
	else
	{
		if(!is_dir($create_folder))
		{
			$create_folder = trim($create_folder, "/");
			$folderParent = substr($create_folder, 0, strrpos($create_folder, "/"));
			
			$child = explode("/", $create_folder);
			$dirname = $child[count($child)-1];
			//echo "<br>create_folder: ". $create_folder;
			//echo "<br>folderParent: ". $folderParent;
			//echo "<br>dirname: ". $dirname;
			
			if($folderParent == "" || $dirname == "")
				return false;
			
			define(DS, DIRECTORY_SEPARATOR);
			define(PATH_ROOT, DS."public_html" );
			
			define("FTP_SERVER","112.213.89.25");
			define("FTP_USERNAME","foodb2bt");
			define("FTP_PASSWORD","0906668453");
		
			$conn_id = ftp_connect(FTP_SERVER);  
			$login_result = ftp_login($conn_id, FTP_USERNAME, FTP_PASSWORD);
			ftp_chdir($conn_id, PATH_ROOT.DS.$folderParent);#DI DEN THU MUC NGUON
		
			if ( ftp_mkdir($conn_id, $dirname) )
			{
			 $dir= PATH_ROOT.DS.$folderParent.DS.$dirname;
			 @ftp_site($conn_id, "CHMOD 777 $dir");
			}  
			
			ftp_close($conn_id);
		}
		return true;
	}
	*/
}
function delete_file($path)
{
  if($path == "")
	return false;
  if(file_exists($path))
  {
	if(@unlink($path))
		return true;
  }
  return false;
}/*
function get_file_name_dont_use($file_title, $renameFile = false)
{
	$ext_arr = split("\.",basename($file_title));
	$fileName = strtolower($ext_arr[count($ext_arr)-2]);
	$fileName = str_replace(" ", "", $fileName);
	$fileName = str_replace("'", "", $fileName);
	$fileName = remove_special_character($fileName);
	if($renameFile)
	   $fileName .= '_' . date("Ymd") . '_' . date("Hms");
	return $fileName;
}*/
function get_file_name_without_extension($path_file)
{
	$filename = "";
	if( strlen( $path_file ) > 0 )
	{
		$path_parts = pathinfo($path_file);
		$filename = $path_parts["filename"];
	}
	return $filename;
}
function get_extension($file_title)
{	
	$pathinfo = pathinfo(basename($file_title));
	$ext = $pathinfo["extension"];
	return $ext;
}
function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2) {
		$vowels .= "AEUY";
	}
	if ($strength & 4) {
		$consonants .= '23456789';
	}
	if ($strength & 8) {
		$consonants .= '@#$%';
	}

	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}
//End Create link of Title page
function render_hidden_form_get_method($arrPara = array())
{
	$str = "";
	$cmd = preg_split("/[?&]/", selfURL());
	foreach($cmd as $item)
	{
		$arr = preg_split("/[=]/", $item);
        $name = isset($arr[0]) ? $arr[0] : "";
        $value = isset($arr[1]) ? $arr[1] : "";
        
		if( $name != "" && $value != "" && !in_array($name, $arrPara))
			$str .= "<input type=\"hidden\" name=\"$name\" id=\"$name\" value=\"$value\" />";
	}
	return $str;
}

function render_hidden_form_post_method($arrPara = array())
{
	$str = "";
	foreach($arrPara as $key=>$value)
	{
		if( $key != "")
			$str .= "<input type=\"hidden\" name=\"$key\" id=\"$key\" value=\"$value\" />\n";
	}
	return $str;
}

function unset_post_method($arrPara = array())
{
	foreach($arrPara as $field)
	{
		if( $field != "")
			unset($_POST[$field]);
	}
}

function out_monney($price)
{
	$price = number_format($price, 0, '.', '.');
	return $price;
}
function out_FCKeditor($str)
{
	$str = str_replace("\\r\\n", "", $str);
	return $str;
}
function cut_string_for_name($str, $max_lenght, $option=" ", $optional="0")
{
	if( mb_strlen($max_lenght,'utf-8') == 0 )
	{
		//Set default max lenght
		$max_lenght = 10;
	}
	if( mb_strlen($str,'utf-8') > $max_lenght )
	{
		if($option != '' &&  strpos($str,$option) == TRUE )
		{
			$str = substr($str, 0, $max_lenght);
			$str = substr($str, 0, strrpos($str,$option));
		}
		else
		{
			$str = substr($str, 0, $max_lenght);			
		}
		$str = trim($str)."...";
	}
	//elseif(  mb_strlen($str,'utf-8') > 0 && $optional=="0")
	//{
		//$str .= "...";
	//}

	return $str;
}
function getIPAddress()
{
	if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
	{
	  $ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	{
	  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else
	{
	  $ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}
function getUserAgent($str_user_agent)
{
    $agent = null;
    if ( empty($agent) ) {
        $agent = $str_user_agent;

        if ( stripos($agent, 'Firefox') !== false ) {
            $agent = 'firefox';
        } elseif ( stripos($agent, 'MSIE') !== false ) {
            $agent = 'ie';
        } elseif ( stripos($agent, 'iPad') !== false ) {
            $agent = 'ipad';
        } elseif ( stripos($agent, 'Android') !== false ) {
            $agent = 'android';
        } elseif ( stripos($agent, 'Chrome') !== false ) {
            $agent = 'chrome';
        } elseif ( stripos($agent, 'Safari') !== false ) {
            $agent = 'safari';
        } elseif ( stripos($agent, 'AIR') !== false ) {
            $agent = 'air';
        } elseif ( stripos($agent, 'Fluid') !== false ) {
            $agent = 'fluid';
        }

    }
    return $agent;
}
function remove_special_character($str)
{
	$str = preg_replace('/[^a-zA-Z0-9]/', '', $str); 
	return $str;
}

function get_subject_by_length($str, $max_lenght, $option=" ", $optional="0")
{
	if( strlen($max_lenght) == 0 )
	{
		//Set default max lenght
		$max_lenght = 10;
	}
	if( mb_strlen($str) > $max_lenght )
	{
		$str = substr($str, 0, $max_lenght);
		if( strpos($str,$option) == TRUE )
		{
			$str = substr($str, 0, strrpos($str,$option))."...";
		}
		else
		{
			$str = substr($str, 0, $max_lenght)."...";
		}
	}
	elseif(  mb_strlen($str) > 0 && $optional=="0")
	{
		$str .="...";
	}

	return $str;
}
function get_recursive_categories($sql, $orderBy = "", $parent_id = 0, $level = 0, $trees = NULL)
{
	if(!$trees) $trees = array();
	$sql_ex = $sql . "$parent_id $orderBy";
	$rows = $GLOBALS['db_mysql']->query($sql_ex);
	$totalRows = $GLOBALS['db_mysql']->affected_rows;
	if($totalRows > 0)
	{
		while($row = $GLOBALS['db_mysql']->fetch_array($rows))
		{
			 $row['level'] = $level;
			 $row['have_sub_menu'] = 0;
			 $trees[] = $row;
			 $trees = get_recursive_categories($sql, $orderBy, $row['id'], $level+1, $trees);
		}
	}
	if(count($trees) > 0)
	{
		$i = 0;
		foreach($trees as $k=>$row)
		{
			if(categories_have_sub_menu($trees, $row['id']))
			{
				$trees[$i]['have_sub_menu'] = 1;
			}
			$i++;
		}
	}
	return $trees;
}
function categories_have_sub_menu($arrRows, $left_cate_id)
{
	if(count($arrRows) > 0)
	{
		foreach($arrRows as $k=>$row)
		{
			if($left_cate_id == $row['parent_id'])
				return true;
		}
	}
	return false;
}
function buil_arr_bussiness_scope()
{
	$sql = "Select * From bussiness_scope Where activate  = 1";		
	$rows = $GLOBALS['db_mysql']->query($sql);
	$totalRows = $GLOBALS['db_mysql']->affected_rows;
	$arr_bussiness_scope = array();
	$bussiness_scope = $_POST['bussiness_scope'];
	if(!is_array($bussiness_scope))
		$bussiness_scope = array();
	if ($totalRows > 0)
	{
		while($row = $GLOBALS['db_mysql']->fetch_array($rows))
		{
			$bussiness_scope_id = $row['bussiness_scope_id'];
			$arr_bussiness_scope[$bussiness_scope_id] = in_array($bussiness_scope_id,$bussiness_scope) ? $bussiness_scope_id : "0";			
		}
		
	}
	return $arr_bussiness_scope;
}
function buil_arr_bussiness_scope_membership_id($membership_id,$arr_bussiness_scope)
{
	$sql = "Select * From membership_bussiness_scope Where membership_id  = '$membership_id'";		
	$rows = $GLOBALS['db_mysql']->query($sql);
	$totalRows = $GLOBALS['db_mysql']->affected_rows;
	
	if ($totalRows > 0)
	{
		while($row = $GLOBALS['db_mysql']->fetch_array($rows))
		{
			$bussiness_scope_id = $row['bussiness_scope_id'];
			$arr_bussiness_scope[$bussiness_scope_id] = $bussiness_scope_id;			
		}
		
	}
	return $arr_bussiness_scope;
}
function get_full_categories($cate_id,$lang,$type="id")
{					
	if($cate_id == "")
	{
		return $type == "id"? "": " Please select a category";
	}
	$sql = "select * from categories where cate_id='".$cate_id."'";		
	$rows = $GLOBALS['db_mysql']->query($sql);
	$totalRows = $GLOBALS['db_mysql']->affected_rows;
	if ($totalRows > 0 && $row = $GLOBALS['db_mysql']->fetch_array($rows))
	{
		if($type == "text")
		{
			$commonCategoryName = $row["category_name_".$lang];
			//$commonCategoryName = $row["category_name_vn"];
		}
		else 
		{
			$commonCategoryName = $row["cate_id"];
		}																
		$parent_id = $row["parent_id"];
		if($parent_id != 1 && $parent_id != 2 && $parent_id != 3 && $parent_id != 4)
		{
			$commonCategoryName = get_full_categories($parent_id,$lang,$type). " >> ".$commonCategoryName;
		}
		return $commonCategoryName;						
	}					
}
function translate_a_word($word, $from_lang='en', $to_lang='vi')
{
	$google_translate = new clsGoogleTranslate();
	$result = $google_translate->translate($word, $from_lang, $to_lang);
	if(trim($result) == "") $result = $word;
	return $result;
}
function get_link_cate($cate_id)
{
	$first_cate = $cate_id;
	$str_breakum = "";
	if($cate_id > 0)
	{
		$sql = "Select parent_id, cate_id, category_name".LANG." as title From categories Where cate_id = ";
		$arrListTitle = get_array_root($sql, $cate_id);
		$arrListTitle = array_reverse($arrListTitle);
		foreach($arrListTitle as $items)
		{
			$css = ($first_cate == $items['cate_id']) ? "current" : "";
			$cate_id = $items['cate_id'];
			$str_breakum .= "<a href='categories.php?cate_id=$cate_id' class='$css'>" . $items['title'] . "</a>";
		}
	}
	return $str_breakum;
}
function get_link_type_categories_contact($page, $product_id, $text)
{
	if(curPageName() == "categories_membership.php")
	{
		$text = "Edit";
		$left_group_product = isset($_GET['left_group_product']) && $_GET['left_group_product'] != "" ? $_GET['left_group_product'] : "selling";
		$page = $left_group_product == "selling" ? "add_selling.php" : "add_buying.php";
		$current_url = selfURL();
		$current_url = urlencode($current_url);		
		$page .= "?product_id=$product_id&source=$current_url";
		return "<a href=\"$page\" class=\"button-blue-mail\">$text</a>";	
	}
	else
	{
		return "<a href=\"$page?product_id=$product_id\" class=\"button-blue-mail\" target=\"_blank\">$text</a>";	
	}
}
function get_link_type_categories_viewdetail($page_detail, $product_id, $text)
{
	if(curPageName() == "categories_membership.php")
	{
		$text = "Delete";
		return " <a href=\"javascript:delete_categories($product_id)\" class=\"button-red-checked\">$text</a>";
	}
	else
	{
		return " <a href=\"$page_detail\" class=\"button-red-checked\">$text</a>";
	}
}
function get_sale_off_icon($hot_deal_discount)
{
	if($hot_deal_discount != "")
		return "<li><span class=\"sale-off-icon\">$hot_deal_discount%</span></li>";
	return "";	
}
function get_sale_off_icon_product_type($hot_deal_discount)
{
	if($hot_deal_discount != "")
		return "<li><span class=\"sale-off-icon-product_type\">$hot_deal_discount%</span></li>";
	return "";	
}
function copy_image_to_library($upload_location,$source_image,$member_id)
{
	create_dir("uploads/membership/$member_id/");
	create_dir("uploads/membership/$member_id/image_library/");
	create_dir("uploads/membership/$member_id/image_library/products");
	$library_image_url =  str_replace($upload_location,"uploads/membership/$member_id/image_library/products/",$source_image);
	$library_image_url = str_replace("large.",date("ymd_hi").".",$library_image_url);	
	copy($source_image,$library_image_url);	
}
function replace_for_javascript($str)
{
 $str = str_replace(chr(13), '', $str);
 $str = str_replace("'","\'",$str);
 return $str;
}
function addGoogleEvents($page,$object,$lang="",$label="",$event=true,$action="onmousedown",$value="")
{
    //return ""; 
    $action = replace_for_javascript($action);
    $label = replace_for_javascript($label);
    $category = $page."_".$object;
    if($lang != "")
    $category .= "_".$lang;
    $category =replace_for_javascript($category);
	
	 if($event)
	 {
	  return "$action=\"_gaq.push(['_trackEvent','$category', '$action', 		'$label']);_gaq.push(['secondTracker._trackEvent','$category', '$action', '$label'])\"";
	
	 }
	 else
	 {
	  return ";_gaq.push(['_trackEvent','$category', '$action', '$label']);_gaq.push(['secondTracker._trackEvent','$category', '$action', '$label'])";
	 }
    /*if($event)
    {
        return "$action=\"_gaq.push(['_trackEvent','$category', '$action', '$label'])\"";
    }
    else
    {
        return ";_gaq.push(['_trackEvent','$category', '$action', '$label'])";
    }*/
}
//Minisite start
function string_replace_to_javascript($str)
{

	$str = str_replace(chr(13), '', $str);
	$str = str_replace("\n", '', $str);
	$str = htmlspecialchars($str, ENT_QUOTES);
	$str = str_replace("&lt;", '<', $str);
	$str = str_replace("&gt;", '>', $str);
	//$str = str_replace("'", "&#39;", $str);
	return $str;
}
	
// add custom checkbox
function addCustomCheckbox($name, $label, $ischecked = 0, $unchecked_style="custom_checkbox_unchecked", $checked_style="custom_checkbox_checked", $dump_text = "")
{
	return ("<div ".$dump_text." unchecked='".$unchecked_style."' checked='".$checked_style."' class='custom_checkbox ".($ischecked?$checked_style:$unchecked_style)."'><input type='hidden' name='".$name."' id='".$name."' value='".$ischecked."'> ".$label."</div>");
}

function str_xml2array($contents, $get_attributes=1, $priority = 'tag') 
{
	if(!$contents) return array();

	if(!function_exists('xml_parser_create')) {
		//print "'xml_parser_create()' function not found!";
		return array();
	}

	//Get the XML parser of PHP - PHP must have this module for the parser to work
	$parser = xml_parser_create('');
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	xml_parse_into_struct($parser, trim($contents), $xml_values);
	xml_parser_free($parser);

	if(!$xml_values) return;//Hmm...

	//Initializations
	$xml_array = array();
	$parents = array();
	$opened_tags = array();
	$arr = array();

	$current = &$xml_array; //Refference

	//Go through the tags.
	$repeated_tag_index = array();//Multiple tags with same name will be turned into an array
	foreach($xml_values as $data) {
		unset($attributes,$value);//Remove existing values, or there will be trouble

		//This command will extract these variables into the foreach scope
		// tag(string), type(string), level(int), attributes(array).
		extract($data);//We could use the array by itself, but this cooler.

		$result = array();
		$attributes_data = array();
		
		if(isset($value)) {
			if($priority == 'tag') $result = $value;
			else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
		}

		//Set the attributes too.
		if(isset($attributes) and $get_attributes) {
			foreach($attributes as $attr => $val) {
				if($priority == 'tag') $attributes_data[$attr] = $val;
				else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
			}
		}

		//See tag status and do the needed.
		if($type == "open") {//The starting of the tag '<tag>'
			$parent[$level-1] = &$current;
			if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
				$current[$tag] = $result;
				if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
				$repeated_tag_index[$tag.'_'.$level] = 1;

				$current = &$current[$tag];

			} else { //There was another element with the same tag name

				if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					$repeated_tag_index[$tag.'_'.$level]++;
				} else {//This section will make the value an array if multiple tags with the same name appear together
					$current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
					$repeated_tag_index[$tag.'_'.$level] = 2;
					
					if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
						$current[$tag]['0_attr'] = $current[$tag.'_attr'];
						unset($current[$tag.'_attr']);
					}

				}
				$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
				$current = &$current[$tag][$last_item_index];
			}

		} elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
			//See if the key is already taken.
			if(!isset($current[$tag])) { //New Key
				$current[$tag] = $result;
				$repeated_tag_index[$tag.'_'.$level] = 1;
				if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;



			} else { //If taken, put all things inside a list(array)
				if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

					// ...push the new element into that array.
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					
					if($priority == 'tag' and $get_attributes and $attributes_data) {
						$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
					}
					$repeated_tag_index[$tag.'_'.$level]++;

				} else { //If it is not an array...
					$current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
					$repeated_tag_index[$tag.'_'.$level] = 1;
					if($priority == 'tag' and $get_attributes) {
						if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
							
							$current[$tag]['0_attr'] = $current[$tag.'_attr'];
							unset($current[$tag.'_attr']);
						}
						
						if($attributes_data) {
							$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
						}
					}
					$repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
				}
			}

		} elseif($type == 'close') { //End of tag '</tag>'
			$current = &$parent[$level-1];
		}
	}
	
	return($xml_array);
} 
function xml2array($url, $get_attributes = 0, $priority = 'tag')
{
	$contents = "";
	if (!function_exists('xml_parser_create'))
	{
		return array ();
	}
	$parser = xml_parser_create('');
	if (!($fp = @ fopen($url, 'rb')))
	{
		return array ();
	}
	while (!feof($fp))
	{
		$contents .= fread($fp, 8192);
	}
	fclose($fp);
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	xml_parse_into_struct($parser, trim($contents), $xml_values);
	xml_parser_free($parser);
	if (!$xml_values)
		return; //Hmm...
	$xml_array = array ();
	$parents = array ();
	$opened_tags = array ();
	$arr = array ();
	$current = & $xml_array;
	$repeated_tag_index = array (); 
	foreach ($xml_values as $data)
	{
		unset ($attributes, $value);
		extract($data);
		$result = array ();
		$attributes_data = array ();
		if (isset ($value))
		{
			if ($priority == 'tag')
				$result = $value;
			else
				$result['value'] = $value;
		}
		if (isset ($attributes) and $get_attributes)
		{
			foreach ($attributes as $attr => $val)
			{
				if ($priority == 'tag')
					$attributes_data[$attr] = $val;
				else
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
			}
		}
		if ($type == "open")
		{ 
			$parent[$level -1] = & $current;
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
			{
				$current[$tag] = $result;
				if ($attributes_data)
					$current[$tag . '_attr'] = $attributes_data;
				$repeated_tag_index[$tag . '_' . $level] = 1;
				$current = & $current[$tag];
			}
			else
			{
				if (isset ($current[$tag][0]))
				{
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
					$repeated_tag_index[$tag . '_' . $level]++;
				}
				else
				{ 
					$current[$tag] = array (
						$current[$tag],
						$result
					); 
					$repeated_tag_index[$tag . '_' . $level] = 2;
					if (isset ($current[$tag . '_attr']))
					{
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
						unset ($current[$tag . '_attr']);
					}
				}
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
				$current = & $current[$tag][$last_item_index];
			}
		}
		elseif ($type == "complete")
		{
			if (!isset ($current[$tag]))
			{
				$current[$tag] = $result;
				$repeated_tag_index[$tag . '_' . $level] = 1;
				if ($priority == 'tag' and $attributes_data)
					$current[$tag . '_attr'] = $attributes_data;
			}
			else
			{
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
				{
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
					if ($priority == 'tag' and $get_attributes and $attributes_data)
					{
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
					}
					$repeated_tag_index[$tag . '_' . $level]++;
				}
				else
				{
					$current[$tag] = array (
						$current[$tag],
						$result
					); 
					$repeated_tag_index[$tag . '_' . $level] = 1;
					if ($priority == 'tag' and $get_attributes)
					{
						if (isset ($current[$tag . '_attr']))
						{ 
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
							unset ($current[$tag . '_attr']);
						}
						if ($attributes_data)
						{
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
						}
					}
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
				}
			}
		}
		elseif ($type == 'close')
		{
			$current = & $parent[$level -1];
		}
	}
	return ($xml_array);
}
function subval_sort($array, $id="id", $sort_ascending=false) {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if (isset($item[$id])) {
                                    if ($array[$lowest_id][$id]) {
                    if ($item[$id]<$array[$lowest_id][$id]) {
                        $lowest_id = $index;
                    }
                    }
                                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
                if ($sort_ascending) {
            return $temp_array;
                } else {
                    return array_reverse($temp_array);
                }
    }
	
function getFileContentCurl( $url, $timeout = 300 )
{
	
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout);
	curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );// require for ssl
	//$cookie = tempnam ("/tmp", "CURLCOOKIE");
	//curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
	//curl_setopt( $ch, CURLOPT_ENCODING, "" );
	//curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
	//curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
	//curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
	//curl_setopt($curl, CURLOPT_POST, true);
	//curl_setopt($curl, CURLOPT_POSTFIELDS, $args);
	$content = curl_exec($ch);
	$respond_info = curl_getinfo($ch);
	curl_close($ch);		
	if($respond_info['http_code'] === 200)
	{
		return $content;
	}
	else
	{
		return "";
	}	
	
}
function get_external_service($url)
{
	$result  =  file_get_contents($url);
	//$result  =  getFileContentCurl($url);
	return $result;
}
function setVar($v, $l, $db_input = false) 
{
	$result = "";
	if (isset($_REQUEST[$v])) 
	{
		$result = trim($_REQUEST[$v]);
	} 
	else 
	{
		$result = $l;
	}
	if($db_input)
		$result = $GLOBALS["db_mysql"]->db_input($result);
	return $result;
}
//////////
//minhhung
//////////
function create_thumb($srcname="",$destname="",$maxwidth=0,$maxheight=0 , &$error = "")
{
    $oldimg = $srcname;
    $newimg = $destname;

    $error = "";
    if( $oldimg == "" )
    {
         $error .= "<p>Invalid path source";
    }
    if ($newimg == "" )
    {
        $error .= "<p>Invalid path destination";
    }
    if(!file_exists($oldimg))
    {
        $error .= "<p>Invalid path source $oldimg";  
    }
    
    if($maxwidth == 0)
    {
       $error .= "<p>Invalid maxwidth $maxwidth"; 
    } 
    
    if($maxheight == 0)
    {
         $error .= "<p>Invalid maxheight $maxheight"; 
    }
    
    if($error!="")
        return false;
    
    list($imagewidth,$imageheight,$imagetype)=@getimagesize($oldimg);

    $shrinkage = 1;
    if ($imagewidth > $maxwidth)
        $shrinkage = $maxwidth/$imagewidth;
    
    if($shrinkage !=1)
    {
        $dest_height = $shrinkage * $imageheight;
        $dest_width = $maxwidth;
    }
    else
    {
        $dest_height=$imageheight;
        $dest_width=$imagewidth;
    }
    if($dest_height > $maxheight)
    {
        $shrinkage = $maxheight/$dest_height;
        $dest_width = $shrinkage * $dest_width;
        $dest_height = $maxheight;
    }
    if($imagetype==2)
    {
        $src_img = imagecreatefromjpeg($oldimg);
        $dst_img = imagecreatetruecolor($dest_width, $dest_height);
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $imagewidth, $imageheight);
        imagejpeg($dst_img, $newimg, 75);
        imagedestroy($src_img);
        imagedestroy($dst_img);
    }

    elseif ($imagetype == 3)
    {
        $src_img = imagecreatefrompng($oldimg);
        $dst_img = imagecreatetruecolor($dest_width, $dest_height);
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $imagewidth, $imageheight);
        imagepng($dst_img, $newimg, 75);
        imagedestroy($src_img);
        imagedestroy($dst_img);
    }
    else
    {
        $src_img = imagecreatefromgif($oldimg);
        $dst_img = imagecreatetruecolor($dest_width, $dest_height);
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $imagewidth, $imageheight);
        imagegif($dst_img, $newimg, 75);
        imagedestroy($src_img);
        imagedestroy($dst_img);
    }
    
    return true;
}

function create_watermark($path_source="",$path_destination="",$postion="top-left", &$error="")
{
    $s_img = null;   
    $s_width = 0;
    $s_height = 0;
    $s_type = "";   
    
    $d_img = null;
    $d_width = 0;
    $d_height = 0;
    $d_type = 0;
        
    $error= "";
    if($path_source=="" ) 
    {
        $error .= "<p>Invalid path source";
    }
    if ($path_destination == "" )
    {
        $error .= "<p>Invalid path path_destination";
    }
    if( !file_exists($path_source)) {
        $error .= "<p>File source not exist $path_source";
    }
    
    if( !file_exists($path_destination)) 
    {
        $error .= "<p>File destination not exist $path_source";
    }
    
    if ($error !="")
        return false;
    
    //lay thong tin source
    list($s_width,$s_height,$s_type)= getimagesize($path_source);
    //lay thong tin destination
    list($d_width,$d_height,$d_type)= getimagesize($path_destination);
    
    switch ($s_type)
    {
        case IMAGETYPE_JPEG:
            $s_img = imagecreatefromjpeg($path_source);
        break;
        case IMAGETYPE_GIF:
            $s_img = imagecreatefromgif($path_source);
        break;
        case IMAGETYPE_PNG: 
            $s_img = imagecreatefrompng($path_source);            
        break; 
    }
    
    switch ($d_type)
    {
         case IMAGETYPE_JPEG:
            $d_img = imagecreatefromjpeg($path_destination);
        break;
        case IMAGETYPE_GIF:
            $d_img = imagecreatefromgif($path_destination);
        break;
        case IMAGETYPE_PNG: 
            $d_img = imagecreatefrompng($path_destination);            
        break; 
    }
    
    //xu ly watermark
    
    $arr_temp = explode ("-",$postion);
    $align = $arr_temp[1];
    $valign = $arr_temp[0];
    
    //vi trí x c?a wtm
    $d_x = 0;
    //vi trí y c?a wtm
    $d_y = 0;
    
    switch ($align)
    {
        case "left":
            $d_x= 0;
        break;
        case "right":
            $d_x = $d_width - $s_width;
        break;
        case "center":
            $d_x = ($d_width - $s_width)/2;
        break;
    }
    
    switch ($valign)
    {
        case "top":
            $d_y= 0;
        break;
        case "bottom":
            $d_y = $d_height - $s_height ;
        break;
        case "center":
            $d_y = ($d_height - $s_height)/2 ;
        break;
    }
    
    $rs = imagecopy($d_img, $s_img ,  $d_x ,$d_y ,  0 , 0 , imagesx($s_img), imagesy($s_img));
    
    //gan hinh tro lai 
    switch ($d_type)
    {
    
         case IMAGETYPE_JPEG:
            imagejpeg( $d_img ,  $path_destination, 100);
        break;
        case IMAGETYPE_GIF:            
             imagegif($d_img, $path_destination, 100);
        break;
        case IMAGETYPE_PNG: 
            imagepng($d_img, $path_destination, 100);
                      
        break; 
    }
    
    imagedestroy($d_img);
    imagedestroy($s_img);
    return $rs;     
}

function create_image($file_name ="", $color_code, $width=0, $height=0, &$error=false)
{
    //kiem tra
    if( strlen( trim( $color_code ) ) !=7 || substr($color_code , 0, 1) != "#" ) 
        $error[] = "Invalid color code";
        
    if( $width == 0 )
        $error[] = "Width must greater than 0";
        
    if( $height == 0 )
        $error[] = "Height must greater than 0";
    
    preg_match("/\.([^\.]+)$/", $file_name , $maches );
    $type = isset( $maches[1] ) ? $maches[1] : "";
    if($type == "" ||( $type !="gif" && $type !="png" && $type !="jpg" ) )
       $error[] = "Invalid file extention"; 
    
    if($error == false)    
        $img = imagecreate($width , $height) or $error[] = "GD is not installed"; 
     
    if($error == false)
    {
        //tao mau 
        $red = "0x" . substr($color_code , 1,2);
        $green = "0x" . substr($color_code,3,2);
        $blue = "0x". substr($color_code,5,2);
        
        imagecolorallocate($img , $red , $green , $blue);
         
        //xuat hinh       
        $rs = false;
        switch ($type)
        {
            case "gif":
               $rs = imagegif($img,$file_name);
            break;
            case "png":
                $rs = imagepng($img,$file_name);
            break;
            case "jpg":
                $rs = imagejpeg($img,$file_name);
            break;           
        }
        
        //free memmory
        imagedestroy($img);
        return $rs;
    }   
    return false;   
}

function destroy_dir($dir, $virtual = false)
{
    $ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
    if (is_dir($dir) && $handle = opendir($dir))
    {
        while ($file = readdir($handle))
        {
            if ($file == '.' || $file == '..')
            {
                continue;
            }
            elseif (is_dir($dir.$ds.$file))
            {
                destroy_dir($dir.$ds.$file);
            }
            else
            {
                unlink($dir.$ds.$file);
            }
        }
        closedir($handle);
        rmdir($dir);
        return true;
    }
    else
    {
        return false;
    }
}

	function get_cookie_session($name, $default_value = null) {
		$value = $default_value;
		
		if (isset($_SESSION[$name])) {
			$value = $_SESSION[$name];
		}
		else if (isset($_COOKIE[$name])) {
			$value = $_COOKIE[$name];
		}
		
		return $value;
	}
	
	function set_cookie_session($name, $value, $longtime = false) {
		$_SESSION[$name] = $value;
		setcookie($name, $value, ($longtime == true ? (time() + 365 * 24 * 60 * 60) : 0), '/');
	}
	
	function delete_cookie_session($name) {
		$_SESSION[$name] = '';
		unset($_SESSION[$name]);
		setcookie($name, '', time() - 1000, '/');
	}

	function echo_json($result) {
		header('Content-Type: text/javascript; charset=UTF-8');		
		echo json_encode($result);
	}
		
	function echo_jsonp($callback, $result) {
		header('Content-Type: text/javascript; charset=UTF-8');
		echo $callback. '(' . json_encode($result) . ')';
	}
	
	function load_file_content($file, $lang) {
		ob_start();
		
		if (file_exists($file)) {
			include_once($file);
		}
		
		$output = ob_get_contents();
		ob_end_clean();
		
		return $output;
	}
	
	function get_cache($key) {
		if (isset($_SESSION['cache_' . $key])) {
			return $_SESSION['cache_' . $key];
		}
	}

	function set_cache($key, $value) {
		$_SESSION['cache_' . $key] = $value;
	}

	function get_facebook_obj() {
	  require_once(DIR_WS_USER . 'libraries/social_media/facebook/classes/facebook.php');
			
		$facebook = new Facebook(array(
			'appId' => FB_APP_ID,
			'secret' => FB_APP_SECRET,
			'cookie' => true
		));
		
		try {
			$uid = $facebook->getUser();
		}
		catch (FacebookApiException $e) {
			error_log($e);
		}
		
		if ($uid) {
			return $facebook;
		}
		
		return false;
	}

	/* make a URL small */
	function make_bitly_url($url, $login, $appkey, $format = 'xml', $version = '2.0.1') {
	  //create the URL
	  $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
	  
	  //get the url
	  //could also use cURL here
	  $response = file_get_contents($bitly);
	  
	  //parse depending on desired format
	  if(strtolower($format) == 'json') {
	    $json = @json_decode($response,true);
	    return $json['results'][$url]['shortUrl'];
	  }
	  else {
	    $xml = simplexml_load_string($response);
	    return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	  }
	}

	
	
	function signature_removed($input)
	{
		return iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $input);
	}
	function create_zip($files = array(), $destination = '', $overwrite = false) {
		//if the zip file already exists and overwrite is false, return false
		if (file_exists($destination) && !$overwrite) {
			return false;
		}
		//vars
		$valid_files = array();
		//if files were passed in...
		if (is_array($files)) {
			//cycle through each file
			foreach ($files as $file) {
				//make sure the file exists
				if (file_exists($file)) {
					$valid_files[] = $file;
				}
			}
		}
		$zip = new ZipArchive();
		if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
		$folder = "cookies_images";
		if($zip->addEmptyDir($folder)) 
		{
			//if we have good files...
			if (count($valid_files)) {
				//create the archive
				//add the files
				foreach ($valid_files as $file) {
					//if(file_exists($file))
						$zip->addFile($file, $folder."/".basename($file));
				}
				
			} /*else {
				return false;
			}	*/			
		}
		else 
		{
			$zip->close();
			return false;
		}
		//debug
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
		//close the zip -- done!
		$zip->close();
 
		//check to make sure the file exists
		return file_exists($destination);		
		
	}
	function removed_dir($sourceDir, $destinationDir)
	{
		$files = scandir($sourceDir);
		$delete = array();
		foreach ($files as $file)
		{  
			if (in_array($file, array(".",".."))) continue;
			// If we copied this successfully, mark it for deletion
			if (copy($sourceDir.$file, $destinationDir.$file)) {
				$delete[] = $sourceDir.$file;
			}
		}
		// Delete all successfully-copied files
		foreach ($delete as $file) {
			@unlink($file);
		}
		
		@rmdir($sourceDir);
	}
    
    function delete_uploaded_file($dir, $rmdir = false)
    {
        if( strpos($dir , DIR_WS_USER."uploads" ) === false) return false;
        if(is_dir($dir) )
        {
            $arr1 = scandir($dir);
            for($i = 2 ; $i<count($arr1); $i++)
            {
                $file = $dir.$arr1[$i];
                
                if(file_exists($file))
                {
                    unlink($file);
                }
            }
            if($rmdir)
                rmdir($dir);  
        }
    }
function name_image ($name = "",$original = "",$type = "")
{
    if($name != "")
        return str_replace(array("_$original.jpg","_$original.png","_$original.gif","_$original.jpeg"), array("_$type.jpg","_$type.png","_$type.gif","_$type.jpeg"), $name);
    return "";
}
//hung
function activeItems($data = array())
{
    global $db_mysql; 
    if (isset($_POST['hidden_submitType']) && $_POST['hidden_submitType'] == 'update' && count($data)) 
    {   
        list($table, $pkey) = each($data);
        $arr_activate_id = (isset($_POST['activate_id']) && count($_POST['activate_id'])) ?  $_POST['activate_id'] : array();
        $arr_id = array();
        if(isset($_POST['hidden_str_id']) && strlen($_POST['hidden_str_id']) >0)
        {
            $arr_id = explode(';', $_POST['hidden_str_id'] );
        }
        $str = "";
        foreach($arr_id as $v)
        {
            $v = intval($v);
            if(!in_array($v, $arr_activate_id))
            {
                if(strlen($str) > 0)
                {
                    $str .=",";
                }
                $str.= $v;
            }
        }  
        
        $count = 0;
        $str2 = "";
        if(count($arr_activate_id))
        {
            foreach($arr_activate_id as $v)
            {
                 $str2.= $v*1 . ",";
                 $count ++;
            }
            $str2 = preg_replace("/,$/","",$str2);
        }
        if(count($arr_id) > 0 && strlen($str) > 0)
        {
            $sql = 'UPDATE '.$table.' SET activate = 0 WHERE '.$pkey.' IN ('.$str.') ';
            $db_mysql->query($sql); 
        }
        
        if(count($arr_activate_id) >0 && strlen($str2) > 0)
        {
            $sql = 'UPDATE '.$table.' SET activate = 1 WHERE '.$pkey.' IN ('.$str2.')';
            $db_mysql->query($sql); 
            $message = "Activate $count item(s) successfully";
            clsErrorMessages::addMessage($message, "success");
        }
    }
}

//Hung
//upload files for admin only
function process_upload_files($arr= array(),$table='',$primary_key='',$id=0, $update_db = true)
{
    global $db_mysql;
    //process upload file
    $dir_uploads = DIR_WS_USER . 'uploads/'.$table.'/';
    $dir_temp = DIR_WS_USER . 'uploads/temp/';
    if(!is_dir($dir_uploads))
    {
        create_dir($dir_uploads);
    }
    $dir_uploads .=$id .'/';
    if(!is_dir($dir_uploads)) 
    {
        create_dir($dir_uploads);
    }
    
    $item_upload = '';
    
    $fields_values = array();
    foreach ($arr as $item_upload)
    {
        $hidden_results_image = trim($db_mysql->db_input( setVar ("hidden_results_".$item_upload,""))) ;                                      
        $delete_results_image = isset($_POST["ckDeleteImg_".$item_upload]) && $_POST["ckDeleteImg_".$item_upload] == "on" ? 1 : 0;   
        if($hidden_results_image!="" && file_exists($hidden_results_image))
        {
            //delete old item
            $sql = 'SELECT '.$item_upload.' FROM '.$table.' WHERE '.$primary_key.' = "'.$id.'"';
            $cms_image_url = $db_mysql->get_field_value($sql);
            //echo $sql;
            //echo DIR_WS_USER .$cms_image_url;
            if(file_exists(DIR_WS_USER .$cms_image_url))
            {
                //echo 1;
                $file = DIR_WS_USER .$cms_image_url;
                if(file_exists($file) && is_dir($file) == false) unlink($file);
                
                $file = DIR_WS_USER . str_replace("_original" , "_large" ,  $cms_image_url);
                if(file_exists($file) && is_dir($file) == false) unlink($file);
                
                $file = file_exists(DIR_WS_USER . str_replace("_original" , "_thumb" ,  $cms_image_url)); 
                if(file_exists($file) && is_dir($file) == false)  unlink($file);
            }
            //echo DIR_WS_USER .$cms_image_url;
            //exit;
            $arr_file_info = pathinfo($hidden_results_image);
            $image_original = $dir_uploads . $arr_file_info['filename']."_"."original"."." . $arr_file_info['extension'];
            
            //var_dump($hidden_results_image,$image_original);
            //exit;
            copy($hidden_results_image,$image_original);
            if(file_exists($hidden_results_image)) unlink($hidden_results_image);
            $fields_values[$item_upload] = 'uploads/'.$table.'/'.$id .'/'. $arr_file_info['filename']."_"."original"."." . $arr_file_info['extension'];
        }
        
        else if($delete_results_image == 1)
        {
            $sql = 'SELECT '.$item_upload.' FROM '.$table.' WHERE '.$primary_key.' = "'.$id.'"';
            $cms_image_url = $db_mysql->get_field_value($sql);
            if(file_exists(DIR_WS_USER .$cms_image_url))
            {
                $file = DIR_WS_USER .$cms_image_url;
                if(file_exists($file) && is_dir($file) == false) unlink($file);
                
                $file = DIR_WS_USER . str_replace("_original" , "_large" ,  $cms_image_url);
                if(file_exists($file) && is_dir($file) == false) unlink($file);
                
                $file = file_exists(DIR_WS_USER . str_replace("_original" , "_thumb" ,  $cms_image_url)); 
                if(file_exists($file) && is_dir($file) == false)  unlink($file);
            }
            $fields_values[$item_upload] = '';
        }
    }
    if(count($fields_values) > 0 && $update_db == true)
    {
        if(insert_db($table, $fields_values, $primary_key, $id,0))
        {
            return $fields_values;
        }
    } else
    {
        return $fields_values;
    }
    return false;
}

//hung
function orderItems($data = array() , $pos_col="", $where = "")
{
    
//    $table = 'contents_categories';
//    $pkey = 'cate_id';
//    $pos_col = 'position';
    global $db_mysql;
    if(isset($_POST['hidden_data_order']) && ($_POST['hidden_data_order'] == 'up' || $_POST['hidden_data_order'] == 'down') )
    {       
        list($table, $pkey) = each($data);
        
       
        
        $id = $db_mysql->db_input( $_POST['hidden_selectedItems'] );
        $data_order = $_POST['hidden_data_order'];
        
        if($id > 0)
        {     
            $sql = "SELECT $pos_col FROM $table WHERE $pkey = $id";
            $pos = $db_mysql->get_field_value($sql);
            
            if($data_order == 'up' && $pos > 0)
            {
                $sql = "SELECT $pkey ,  $pos_col FROM $table WHERE $pos_col < $pos $where ". " ORDER BY $pos_col DESC LIMIT 1";    
               
                $rows = $db_mysql->get_array($sql);
                $row = isset($rows[0]) ?  $rows[0] : array();
                
                $message = "Move up 1 item successfully";
            }   else if ($data_order == 'down' && $pos > 0){
                $sql = "SELECT $pkey , $pos_col FROM $table WHERE $pos_col > $pos  $where ". " ORDER BY $pos_col ASC LIMIT 1";    
                
                $media_pos_temp = $db_mysql->get_field_value($sql);
                $rows = $db_mysql->get_array($sql);
                $row = isset($rows[0]) ?  $rows[0] : array();
                
                $message = "Move down 1 item successfully"; 
            }
            
            $id_2 = $row[$pkey];
            $pos_2 = $row[$pos_col];
            if($id_2 > 0)
            {    
                if($pos_2)
                {
                    $sql = "UPDATE $table SET $pos_col = $pos_2 WHERE $pkey = $id " ;
                    $db_mysql->query($sql);
                }
                if($pos)
                {
                    $sql ="UPDATE $table SET $pos_col = $pos WHERE $pkey = $id_2 ";
                    $db_mysql->query($sql);
                }
                clsErrorMessages::addMessage($message, "success");
            }
        }
    }
}
function get_domain_url($url)
{
	if($url != "")
	{
		$url_arr = parse_url($url);
		return  isset($url_arr['host']) && $url_arr['host'] != "" ? $url_arr['host'] :''; 
	}
	else
	{
		return "";
	}
}
function get_domain_HTTP_REFERER()
{
	$http_referer = isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != "" ? $_SERVER['HTTP_REFERER'] : ""; 
	return get_domain_url($http_referer );
}
function parse_signed_request($signed_request, $secret) 
{
	list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	
	// decode the data
	$sig = base64_url_decode($encoded_sig);
	$data = json_decode(base64_url_decode($payload), true);
	
	if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') 
	{
		error_log('Unknown algorithm. Expected HMAC-SHA256');
		return null;
	}
	
	// Adding the verification of the signed_request below
	$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
	if ($sig !== $expected_sig) 
	{
		error_log('Bad Signed JSON signature!');
		return null;
	}

	return $data;
}
function make_signed_request($data, $secret) {
	$data['algorithm'] = 'HMAC-SHA256';
	
	$payload = base64_url_encode(json_encode($data));
	$sig = base64_url_encode(hash_hmac('sha256', $payload, $secret, true));
	
	$signed_request = implode('.', array($sig, $payload));
	
	return $signed_request;
}

function parse_signed_request_Parsing($signed_request) 
{
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  return $data;
}
function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}
function base64_url_encode($input) {
		return strtr(base64_encode($input), '+/', '-_');
}
//hung
function xss_clean($str)
{
    return strip_tags($str);
}

function selfURL_HOST($endcode = false)
{
	//protocol
	if(isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && ($_SERVER["HTTP_X_FORWARDED_PROTO"]== "http"  || $_SERVER["HTTP_X_FORWARDED_PROTO"]== "https" ))
		$protocol = $_SERVER["HTTP_X_FORWARDED_PROTO"];
	else
	{
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;	
	}
	//SERVER_PORT
	if(isset($_SERVER["HTTP_X_FORWARDED_PORT"]) && ($_SERVER["HTTP_X_FORWARDED_PORT"] != ""  ))
	{	
		//$port = $_SERVER["SERVER_PORT"];
		$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	}
	else
	{
		$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	}
	//server name
	if(isset($_SERVER["HTTP_HOST"]) && ($_SERVER["HTTP_HOST"] != ""  ))
	{	
		//$port = $_SERVER["SERVER_PORT"];
		$server_name = $_SERVER["HTTP_HOST"];
	}
	else
	{
		$server_name = $_SERVER["SERVER_NAME"];
	}
	
	$query_string = isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != "" ? "?".$_SERVER['QUERY_STRING'] : "";
	
		
	$url = $protocol."://".$server_name.$port.$_SERVER['PHP_SELF'].$query_string;
	if($endcode)
		$url = urlencode($url);
	return $url;
}

function log_cron_job($message,$file)
{     
    $contents = "\n" . $message . "\n--------";
    $mod= "a+";
    $fs = fopen($file,$mod);
    fwrite($fs,$contents, strlen($contents));
    fclose($fs);
}

function update_last_login($user_id)
{
	$sql = "UPDATE users SET lastlogin = '". date("Y-m-d H:i:s") ."' WHERE user_id = '$user_id'";
	$GLOBALS["db_mysql"]->query($sql);
}

function get_position_by_index($arr_legend, $index, $type)
{
	foreach($arr_legend[$type] as $word)
	{
		if($word["index"] == $index)
			return $word["position"];
	}
}

function legend_to_crossword_data($arr_legend)
{
	foreach($arr_legend["across"] as $word)
	{
//		$arr[$word["index"]] = array("clue"=>$word["clue"], "word"=>$word["word"]);
		$arr[$word["index"]] = $word["word"] . " " . $word["clue"];
	}
	foreach($arr_legend["down"] as $word)
	{
//		$arr[$word["index"]] = array("clue"=>$word["clue"], "word"=>$word["word"]);
		$arr[$word["index"]] = $word["word"] . " " . $word["clue"];
	}
	return implode(PHP_EOL, $arr);
}

function delete_char_grid(&$arr_grid)
{
	for($i = 0; $i<count($arr_grid);$i++)
	{
		for($j = 0; $j<count($arr_grid[$i]); $j++)
		{
			if(is_array($arr_grid[$i][$j]))
			{
				$arr_grid[$i][$j]["char"] = "";
			}
		}
	}
}

function grid_to_words($grid_json)
{
	$arr_grid = json_decode($grid_json, true);
	$arr_words = array();
	for($i = 0; $i<count($arr_grid);$i++)
	{
		for($j = 0; $j<count($arr_grid[$i]); $j++)
		{
			$cell = $arr_grid[$i][$j];
			if(is_array($cell)) // has word
			{
				$char = $cell["char"] != "" ? $cell["char"] : " ";
				if(is_array($cell["across"])) //across
				{
					$index = $cell["across"]["index"];
					if($cell["across"]["is_start_of_word"] == 1)
					{
						$arr_words[$index] = $char;
					}
					else
					{
						$arr_words[$index] .= $char;
					}
				}
				if(is_array($cell["down"])) //down
				{
					$index = $cell["down"]["index"];
					if($cell["down"]["is_start_of_word"] == 1)
					{
						$arr_words[$index] = $char;
					}
					else
					{
						$arr_words[$index] .= $char;
					}
				}
			}
		}
	}
	ksort($arr_words);
	return $arr_words;
}

function calculate_word_correct($user_grid, $crossword_grid)
{
	$word_correct = 0;
	$user_words = grid_to_words($user_grid);
	$crosword_words = grid_to_words($crossword_grid);
	if(count($user_words) == count($crosword_words))
	{
		for($i = 0; $i<count($user_words); $i++)
		{
			if(strtolower($user_words[$i]) === strtolower($crosword_words[$i]))
			{
				$word_correct++;
			}
		}
	}
	return $word_correct;
}

function seconds_to_time($seconds) {
  $t = round($seconds);
  return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}